package vn.edu.saigontech.ncms.service.impl;

import java.util.Collection;
import java.util.Collections;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.criterion.Restrictions;

import vn.edu.saigontech.ncms.model.bookstore.Item;
import vn.edu.saigontech.ncms.model.bookstore.ItemType;
import vn.edu.saigontech.ncms.model.comparator.ItemComparator;
import vn.edu.saigontech.ncms.model.program.Level;
import vn.edu.saigontech.ncms.model.program.Program;
import vn.edu.saigontech.ncms.service.ImportReceiptDetailService;
import vn.edu.saigontech.ncms.service.ItemService;
import vn.edu.saigontech.ncms.util.Checker;

@SuppressWarnings("unchecked")
public class ItemServiceImpl extends HibernateGenericService<Item, Long> implements ItemService {

	@Override
	public Collection<Item> findAll() {
		Criteria criteria = this.createCriteria();
		List<Item> list = criteria.list();
		Collections.sort(list, new ItemComparator());
		return list;
	}
	
	@Override
	public boolean deleteById(Long id) {
		if(!ImportReceiptDetailService.INSTANCE.findByItemId(id).isEmpty())
			return false;
		return super.deleteById(id);
	}	
	
	@Override
	public List<Item> findByType(ItemType type) {
		Criteria criteria = this.createCriteria();
		criteria.add(Restrictions.eq("itemType", type));
		return criteria.list();
	}

	@Override
	public List<Item> filter(Program program, ItemType type) {
		Criteria criteria = this.createCriteria();
		if (!Checker.isNull(type)) {
			criteria.add(Restrictions.eq("itemType", type));
		}
		Criteria titleCriteria = criteria.createCriteria("itemTitle");
		if(!Checker.isNull(program)) {
			titleCriteria.add(Restrictions.eq("program", program));
		}
		List<Item> items = criteria.list();
		Collections.sort(items, new ItemComparator());
		return items;
	}

	@Override
	public Item findByItemId(String itemId) {
		Criteria criteria = this.createCriteria();
		criteria.add(Restrictions.eq("itemId", itemId));
		List<Item> items = criteria.list();
		if(!items.isEmpty()) {
			return items.get(0);
		}
		return null;
	}

	@Override
	public List<Item> findByLevel(Level level) {
		Criteria criteria = this.createCriteria();
		criteria.createCriteria("itemTitle").createAlias("levels", "level", Criteria.LEFT_JOIN);
		criteria.add(Restrictions.eq("level.id", level.getId()));
		List<Item> items = criteria.list();
		Collections.sort(items, new ItemComparator());
		return items;
	}

	@Override
	public List<Item> findByTitleId(Long titleId) {
		Criteria criteria = this.createCriteria();
		criteria.createCriteria("itemTitle").add(Restrictions.eq("id", titleId));
		return criteria.list();
	}
}